package misc

import (
	"dhfshop/controllers/base"
	"dhfshop/models/isv"
	"strings"
	//"github.com/astaxie/beego"
	"github.com/astaxie/beego/validation"
	"wxsdk/mp/card"
)

type WxProxyController struct {
	base.BaseController
}

func (this *WxProxyController) ProxyGet() {
	v := struct {
		ReqMethod       string `form:"req_method" valid:"Required"`
		AuthorizerAppid string `form:"authorizer_appid" valid:"Required"`
		UrlPrefix       string `form:"url_prefix" valid:"Required"`
		Content         string `form:"content"`
	}{}
	this.ParseForm(&v)
	valid := validation.Validation{}
	passed, _ := valid.Valid(&v)
	if !passed {
		this.ServeError(valid.Errors[0].Key + " " + valid.Errors[0].Message)
		return
	}
	var token string
	if custAccount, err := isv.GetCustAccountByAppId(v.AuthorizerAppid); err == nil {
		token = custAccount.AccessToken
	} else {
		if authorize, err := isv.GetAuthorizeByAppId(v.AuthorizerAppid); err == nil {
			token = authorize.AccessToken
		} else {
			this.ServeError(err.Error())
			return
		}
	}
	v.UrlPrefix = strings.Replace(v.UrlPrefix, "TOKEN", token, -1)
	data, err := card.CardProxy(v.ReqMethod, v.UrlPrefix, []byte(v.Content))
	if err != nil {
		this.ServeError(err.Error())
		return
	}
	//this.Ctx.ResponseWriter.Write(data)
	this.Ctx.WriteString(string(data))
}
